#!/usr/bin/py2
# -*- coding: utf-8 -*-
#encoding=utf-8

# @author Funsion Wu
from scrapy.http import Request
from scrapy.pipelines.images import ImagesPipeline
from funsion import settings
from PIL import Image
import os.path

class ImagesPipeline(ImagesPipeline):
    
    def get_media_requests(self, item, info):
        if 'article_image' in item:
            for image_url in item['article_image']:
                yield Request(image_url['original'])
        

    def item_completed(self, results, item, info):
        if 'article_image' in item:
            dispose_image = []
            idx = -1
            for status, image_pipeline in results:
                idx += 1
                original_image = item['article_image'][idx]['original']
                if status:
                    image_local = settings.IMAGES_STORE + image_pipeline['path']
                    image_ftp = settings.REMOTE_URL + image_pipeline['path']
                    image_info = {'local':image_local, 'remote':image_ftp, 'original':original_image, 'upload':'fail' }
                    if os.path.isfile(image_local):
                        image_info['filesize'] = os.path.getsize(image_local)
                        image_info['width'], image_info['height'] = Image.open(image_local).size
                        image_info['upload'] = 'success'

                    if 'article_content' in item:
                        item['article_content'] = item['article_content'].replace( original_image, image_ftp )
                else:
                    image_info = {'original':original_image, 'upload':'fail'}

                dispose_image.append(image_info)

            if dispose_image:
                item['article_image'] = dispose_image

        return item
